package controller {
	import controller.signal.FileUploadChangeSignal;
	import controller.signal.FileUploadProgressSignal;
	
	import flash.events.DataEvent;
	import flash.events.ProgressEvent;
	import flash.net.FileReference;
	import flash.net.URLRequest;
	
	import model.SaveTapeModel;
	
	import org.robotlegs.mvcs.Command;
	
	import service.SaveTapeService;
	
	import subumbo.leg.model.vo.ResizeVO;
	import subumbo.leg.view.signal.ResizeSignal;
	
	import view.progress.Progress;

	public class SaveTapeCommand extends Command {
		
		[Inject] public var tapeModel:SaveTapeModel;
		[Inject] public var saveTapeService:SaveTapeService;
		[Inject] public var uploadProgress:FileUploadProgressSignal;
		[Inject] public var change:FileUploadChangeSignal;
		[Inject] public var resize:ResizeSignal;
		
		private var _fileCount:int;
		private var _progress:Progress;
		private var _paths:Object;
	
		
		public override function execute():void {
			commandMap.detain(this);
			
			_progress = new Progress()
			contextView.addChild(_progress);
			resize.dispatch(new ResizeVO(contextView.stage.stageWidth, contextView.stage.stageHeight));	
			load();
		}		
		
		private function load():void {
			var file:FileReference = FileReference(tapeModel.files[_fileCount]);
			change.dispatch(file.name);
			var request:URLRequest = new URLRequest("http://www.subumbo.com/mixtape/admin/service/upload.php")
			file.upload(request);
			file.addEventListener(DataEvent.UPLOAD_COMPLETE_DATA, onFileUploaded, false, 0 ,true);
			file.addEventListener(ProgressEvent.PROGRESS, onProgress, false, 0 , true);
		}
		
		private function onProgress(e:ProgressEvent):void {
			uploadProgress.dispatch(e.bytesLoaded / e.bytesTotal);
		}	
		
		private function onFileUploaded(e:DataEvent):void {
			var file:FileReference = FileReference(e.target);
			_paths[file.name] = e.target.data.toString();
			file.removeEventListener(DataEvent.UPLOAD_COMPLETE_DATA, onFileUploaded);
			file.removeEventListener(ProgressEvent.PROGRESS, onProgress);
			_fileCount++;
			if(_fileCount == tapeModel.files.length) {
				contextView.removeChild(_progress);
				_progress = null;
				saveInDB();
			} else {
				
				load();
			}
		}
		
		private function saveInDB():void {
			var data:Object = {};
			data.name = tapeModel.name;
			data.label = 
			saveTapeService.loadedSignal.add(onTapeSaved);
			saveTapeService.request.data = data;
			saveTapeService.send();
		}
		
		private function onTapeSaved():void {
			
			commandMap.release(this);
		}
	}
}